//
//  CompanyDetailViewController.m
//  ChengXinBao
//
//  Created by RongZhou on 17/2/21.
//  Copyright © 2017年 RongZhou. All rights reserved.
//

#import "CompanyDetailViewController.h"
#import "CompanyDetailInforCell.h"
#import "WebViewController.h"
#import "CallModel.h"
#import "LLKCollectionManage.h"
#import <Masonry.h>
#import <UIImageView+WebCache.h>
#import <MapKit/MapKit.h>
#import <AFNetworking.h>
#import "UserInforSingal.h"
#define HexRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

@interface CompanyDetailViewController ()<UITableViewDataSource,UITableViewDelegate,MKMapViewDelegate>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSArray *companyArray;
@property(nonatomic,strong)NSMutableArray *detailArray;
@property(nonatomic,strong)MKMapView *mapview;
@property(nonatomic,copy)NSString *phoneNumberArea;
@property(nonatomic,strong)UIImageView *backImg;
@property(nonatomic,copy)NSString *companyIntime;
@end

@implementation CompanyDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"%@",self.companyname);
    NSLog(@"%@",self.companylogo);
    [self getCompanyIntime];
    [self creteUIAboutCompanyInformationDeatile];
    
    // Do any additional setup after loading the view.
}
-(void)viewWillAppear:(BOOL)animated{
    self.view.backgroundColor = [UIColor whiteColor];
    self.tabBarController.tabBar.hidden = YES;
    self.title = @"单位详情";
    [self createRightBaritem];
}
-(void)viewWillDisappear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = NO;
}
/**
 *  创建右收藏按钮
 */
-(void)createRightBaritem{
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.tag = 1000;
    backBtn.frame = CGRectMake(ScreenWidth - 32, 6, 32, 32);
    [backBtn setImage:[UIImage imageNamed:@"collectDefaul"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(rightBarButtonItemPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    [self.navigationItem setRightBarButtonItem:rightButton];
}
/**
 *  创建右边按钮点击事件
 *
 *
 */
-(void)rightBarButtonItemPressed:(UIButton *)btn{
    btn.selected = !btn.selected;
    if (btn.selected) {
        [btn setImage:[UIImage imageNamed:@"collectSelect"] forState:UIControlStateNormal];
        [self addOrCancelCollection:@"1"];
        }else{
        [btn setImage:[UIImage imageNamed:@"collectDefaul"] forState:UIControlStateNormal];
            [self addOrCancelCollection:@"0"];
        }
        NSLog(@"你点了收藏");

}
/**
 *  收藏功能
 */
-(void)addOrCancelCollection:(NSString *)judeStr{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    UserInforSingal *userInfor = [UserInforSingal shareUserinfor];
    NSLog(@"%@",userInfor.userId);
    NSString *url = ServiceUrl@"/collectionApp/addOrCancelCollection";
    NSDictionary *param = @{@"customerId":self.companyWebid,@"phoneUserId":[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"],@"addOrCancel":judeStr};
    NSLog(@"请求体%@",param);
    [manager POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dict);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:dict[@"msg"] message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];

}
/**
 *  创建公司详情界面
 */
-(void)creteUIAboutCompanyInformationDeatile{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight/3)];
    view.backgroundColor = ZColorRGB(34, 68, 104);
    [self.view addSubview:view];
    UIImageView *logoimageView = [[UIImageView alloc] initWithFrame:CGRectZero];
    NSString *str = [NSString stringWithFormat:@"%@/%@",ServiceUrl,self.companylogo];
    NSLog(@"图片的网址%@",str);
    [logoimageView sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:[UIImage imageNamed:@""]];
    [view addSubview:logoimageView];

    [logoimageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view.mas_top).offset(30);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(100);
        make.centerX.equalTo(view.mas_centerX);
    }];
    logoimageView.layer.cornerRadius = 50;
    logoimageView.layer.masksToBounds = YES;
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    nameLabel.text = self.companyname;
    nameLabel.textAlignment = NSTextAlignmentCenter;
    nameLabel.textColor = [UIColor whiteColor];
    [view addSubview:nameLabel];
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(logoimageView.mas_bottom).offset(30);
        make.height.mas_equalTo(20);
        make.left.equalTo(view.mas_left);
        make.right.equalTo(view.mas_right);
    }];
    UILabel *addressLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    addressLabel.text = self.companyaddress;
    addressLabel.textAlignment = NSTextAlignmentCenter;
    addressLabel.textColor = [UIColor whiteColor];
    [view addSubview:addressLabel];
    [addressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(nameLabel.mas_bottom).offset(10);
        make.height.mas_equalTo(20);
        make.left.equalTo(view.mas_left);
        make.right.equalTo(view.mas_right);
    }];
    UIImageView *iconImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
    iconImageView.backgroundColor = [UIColor whiteColor];
    iconImageView.layer.cornerRadius = 10;
    iconImageView.layer.masksToBounds = YES;
    [view addSubview:iconImageView];
    [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view.mas_top).offset(40);
        make.width.mas_equalTo(80);
        make.height.mas_equalTo(20);
        make.left.equalTo(logoimageView.mas_right).offset(1);
    }];
    UIImageView *kexinImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
    kexinImageView.image = [UIImage imageNamed:@"icon_renzheng"];
    [iconImageView addSubview:kexinImageView];
    [kexinImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(iconImageView.mas_left).offset(5);
        make.width.mas_equalTo(20);
        make.height.mas_equalTo(20);
        make.centerY.equalTo(iconImageView.mas_centerY);
    }];
    UILabel *kexinLabel = [[UILabel alloc] init];
    kexinLabel.text = @"可信";
    kexinLabel.textColor = UIColorFromRGB(0xAF704E);
    kexinLabel.textAlignment = NSTextAlignmentCenter;
    [iconImageView addSubview:kexinLabel];
    [kexinLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(kexinImageView.mas_right);
        make.top.equalTo(iconImageView.mas_top);
        make.bottom.equalTo(iconImageView.mas_bottom);
        make.right.equalTo(iconImageView.mas_right);
    }];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"纠错" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    button.layer.borderColor = [UIColor lightGrayColor].CGColor;
    button.layer.borderWidth = 1.0f;
    [button addTarget:self action:@selector(gotoH5:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(ScreenHeight/15);
        make.width.mas_equalTo(ScreenWidth);
        make.bottom.equalTo(self.view.mas_bottom);
        make.left.equalTo(self.view.mas_left);
    }];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view.mas_bottom);
        make.bottom.equalTo(button.mas_top);
        make.left.equalTo(self.view.mas_left);
        make.width.mas_equalTo(ScreenWidth);
    }];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    UIView *tablefooter = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.tableFooterView = tablefooter;
    UINib *nib = [UINib nibWithNibName:@"CompanyDetailInforCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"CompanyDetailInforCell"];
    self.tableView.estimatedRowHeight = 200;

}
/**
 *  进入纠错页面
 *
 *  @param btn
 */
-(void)gotoH5:(UIButton *)btn{
    WebViewController *webVc = [[WebViewController alloc] init];
    [self.navigationController pushViewController:webVc animated:YES];
}
/**
 *  设置imageview的圆角
 *
 *  @param imageView
 */
-(void)setcoridinesAboutImageView:(UIImageView *)
imageView{
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:imageView.bounds.size];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = imageView.bounds;
    maskLayer.path = maskPath.CGPath;
    imageView.layer.mask = maskLayer;
}

/**
 *  根据地名初始化地图
 */
-(void)initMapviewUI:(NSString *)str{
    _mapview = [[MKMapView alloc] initWithFrame:self.tableView.bounds];
    [self.tableView addSubview:_mapview];
    _mapview.mapType = MKMapTypeStandard;
    _mapview.delegate = self;
    [self ForwardCode:str];
}
//正向地理编码
-(void)ForwardCode:(NSString *)str{
    //编码对象
    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
    //正向地理编码
    [geoCoder geocodeAddressString:str completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count == 0) {
            NSLog(@"编码失败");
            return ;
        }
        CLPlacemark *placeMark = [placemarks lastObject];
        NSLog(@"%lf--%lf",placeMark.location.coordinate.latitude,placeMark.location.coordinate.longitude);
        //根据用户位置设置地图的中心点
        [_mapview setCenterCoordinate:placeMark.location.coordinate animated:YES];
        //设置显示范围
        MKCoordinateRegion region;
        region.span.latitudeDelta = 0.01;
        region.span.longitudeDelta = 0.01;
        region.center = placeMark.location.coordinate;
        [_mapview setRegion:region animated:YES];
        
    }];
    
}
-(void)mapViewWillStartLoadingMap:(MKMapView *)mapView{
    NSLog(@"将要开始加载地图");
}
-(void)mapViewDidFinishLoadingMap:(MKMapView *)mapView{
    NSLog(@"完成地图加载");
}
-(void)mapViewDidFailLoadingMap:(MKMapView *)mapView withError:(NSError *)error{
    NSLog(@"地图加载失败%@",error);
}
#pragma mark -tableview的代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
/**
 *  地图大头针显示设置
 *
 *  @param mapView    <#mapView description#>
 *  @param annotation <#annotation description#>
 *
 *  @return <#return value description#>
 */
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    // 获得地图标注对象
    MKPinAnnotationView * annotationView = (MKPinAnnotationView *)[_mapview dequeueReusableAnnotationViewWithIdentifier:@"PIN_ANNOTATION"];
    if (annotationView == nil) {
        annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"PIN_ANNOTATION"];
    }
    // 设置大头针标注视图为紫色
    
    // 标注地图时 是否以动画的效果形式显示在地图上
    annotationView.animatesDrop = YES ;
    // 用于标注点上的一些附加信息
    annotationView.canShowCallout = YES ;
    
    return annotationView;

}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.detailArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CompanyDetailInforCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CompanyDetailInforCell"];
    cell.CompanyLabel.text = self.companyArray[indexPath.row];
    cell.DetailInforLabel.text = self.detailArray[indexPath.row];
    if (indexPath.row == 1) {
        cell.DetailInforLabel.numberOfLines = 1;
        [cell.localtionImageView bringSubviewToFront:cell];
    }
    if (indexPath.row != 1) {
        cell.localtionImageView.hidden = YES;
    }
    if (indexPath.row == 2) {
        cell.DetailInforLabel.textColor = [UIColor blueColor];
    }
    if (indexPath.row == 3) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CompanyDetailInforCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (indexPath.row == 1) {
        [self initMapviewUI:cell.DetailInforLabel.text];
    }
    if (indexPath.row == 2) {
        [self checkPhoneNumberArea:cell.DetailInforLabel.text AndUserName:self.companyname];
    }
    if (indexPath.row == 3) {
        WebViewController *webVc = [[WebViewController alloc] init];
        webVc.companyId = self.companyWebid;
        [self.navigationController pushViewController:webVc animated:YES];
    }
}
-(void)dialPhoneNumber:(NSString *)phoneNUmber AndUsername:(NSString *)userName{
    NSString *MessageStr = [NSString stringWithFormat:@"%@%@",@"tel://",phoneNUmber];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:MessageStr]];
    if (self.phoneNumberArea == nil) {
        self.phoneNumberArea = @"";
    }
    CallModel *model = [[CallModel alloc] initWithUserName:userName AndUserPhonenumber:phoneNUmber AndUserCallTime:[self calueLocalDialPhoneNumberTime] AndUserAddress:self.phoneNumberArea];
    NSLog(@"%@",model.userAddress);
    [[LLKCollectionManage shareManager] addCollect:model];

}
/**
 *  检查手机号码归属地
 *
 *  @param phoneNumber
 */
-(void)checkPhoneNumberArea:(NSString *)phoneNumber AndUserName:(NSString *)userName{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *str = ServiceUrl@"/phoneAreaApp/searchCustomerByPhone?phone=%@";
    NSString *url = [NSString stringWithFormat:str,phoneNumber];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        self.phoneNumberArea = dict[@"area"];
        [self dialPhoneNumber:phoneNumber AndUsername:userName];
        NSLog(@"%@",self.phoneNumberArea);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}
/**
 *  获取当前的拨号时间
 *
 *  @return <#return value description#>
 */
-(NSString *)calueLocalDialPhoneNumberTime{
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    NSDate *date = [NSDate date];
    NSDateFormatter * df = [[NSDateFormatter alloc] init];
    df.dateFormat = @"YYYY年-MM月-dd日 HH:mm";
    [df setTimeZone:sourceTimeZone];//直接指定时区，北京时间
    return [df stringFromDate:date];
}

-(NSArray *)companyArray{
    if (_companyArray == nil) {
        _companyArray = @[@"单位名称",@"单位地址",@"单位电话",@"单位名片",@"入驻时间",@"单位简介"];
    }
    return _companyArray;
}
-(NSMutableArray *)detailArray{
    if (_detailArray == nil) {
        _detailArray = [[NSMutableArray alloc] init];
    }
    return _detailArray;
}
/**
 *  获取企业的入驻时间
 */
-(void)getCompanyIntime{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *str = ServiceUrl@"/customerApp/searchCustomerById?id=%@";
    NSString *url = [NSString stringWithFormat:str,self.companyWebid];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        self.companyIntime = dict[@"createDate"];
        NSString *adress = [NSString stringWithFormat:@"%@%@%@",self.companyCityname,self.companyAreaname,self.companyaddress];
        [self.detailArray addObject:self.companyname];
        [self.detailArray addObject:adress];
        [self.detailArray addObject:self.companyphone];
        [self.detailArray addObject:@" "];
        [self.detailArray addObject:self.companyIntime];
        [self.detailArray addObject:self.companyIntroduce];
        NSLog(@"%@",self.detailArray);
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
